package com.espressif.iot.ui.main;



import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;






import java.util.Set;

import org.apache.log4j.Logger;

import com.espressif.iot.base.application.EspApplication;
import com.espressif.iot.base.net.rest.mesh.EspSocketClient;
import com.espressif.iot.db.IOTDeviceDBManager;
import com.espressif.iot.db.IOTXqzoneDBManager;
import com.espressif.iot.db.greenrobot.daos.DeviceDB;
import com.espressif.iot.db.greenrobot.daos.XqzoneDB;
import com.espressif.iot.device.IEspDevice;
import com.espressif.iot.device.IEspDeviceGateway;
import com.espressif.iot.device.IEspDevicePlug;
import com.espressif.iot.device.IEspDevicePlugXq;
import com.espressif.iot.model.device.EspDeviceCurtainXq;
import com.espressif.iot.model.device.EspDeviceGateway;
import com.espressif.iot.model.device.EspDevicePlug;
import com.espressif.iot.model.device.EspDevicePlugTouchsXq;
import com.espressif.iot.model.device.EspDevicePlugXq;
import com.espressif.iot.model.device.cache.EspDeviceCacheHandler;
import com.espressif.iot.type.device.EspDeviceType;
import com.espressif.iot.type.device.IEspDeviceStatus;
import com.espressif.iot.type.device.state.EspDeviceState;
import com.espressif.iot.type.device.status.EspStatusCurtain;
import com.espressif.iot.type.device.status.EspStatusPlug;
import com.espressif.iot.type.device.status.IEspStatusPlug;
import com.espressif.iot.type.net.IOTAddress;
import com.espressif.iot.user.IEspUser;
import com.espressif.iot.user.builder.BEspUser;
import com.espressif.iot.util.EspStrings;
import com.espressif.iot.util.EspStrings.Key;
import com.espressif.iot.util.InputStreamUtils;
import com.google.zxing.qrcode.ui.ShareCaptureActivity;
import com.lishate.update.GatewayItem;
import com.mob.tools.utils.HEX;
import com.xiquezhijia.iot.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class XqZoneDetailActivty extends Activity implements OnClickListener, OnItemClickListener, OnItemLongClickListener, OnDismissListener{

	private static final Logger log = Logger.getLogger(XqZoneDetailActivty.class);
	private Button back;
	private Button addzone;
	private TextView titlename;
	private GridView devicegridview;
	private List<DeviceDB> devicelist = new ArrayList<DeviceDB>();
	private List<IEspDevice> xqdevicelist = new ArrayList<IEspDevice>();
	private List<IEspDevice> xqcommdevicelist = new ArrayList<IEspDevice>();
	private DeviceAdapter  mdeviceadapter;
	private static IOTDeviceDBManager deviceDBManagerinstance = IOTDeviceDBManager.getInstance();

	private XqzoneDB curzone;
	private static final int REQ_ADDDEVICE= 10001;
	private  boolean isOn ;
	protected IEspUser mUser;
	protected IEspDevice mIEspDevice;
	protected IEspDevice curespdev=null;
	private IEspDevicePlugXq xqplug;
	private String mzonename = null;
	
	//监听添加成功的网关或者插座
	private LocalBroadcastManager mBraodcastManager;
	
	private Set<EspDeviceGateway> gatelist= new HashSet<EspDeviceGateway>();
	
	private  EspSocketClient thiclent =null;
	
	
	private   byte[] xqplugsenddata = {(byte) 0xFE,(byte) 0xE7,0,0,0x0B,0x00,
			0, 0, 0, 0, 0, 0, 0, 0,//MAC ADDR
			0, 0};
	private   byte[] result;
	private   String sendString = null;
	private ProgressDialog mDialog;
	private  List<IOTAddress> gatelocallist;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xqzone_activity);
		back = (Button)findViewById(R.id.left_icon);
		addzone = (Button)findViewById(R.id.right_icon);
		titlename = (TextView)findViewById(R.id.title_text);
		devicegridview = (GridView)findViewById(R.id.zone);
		back.setOnClickListener(this);
		addzone.setOnClickListener(this);
		
		
		
		//ShowCurrentZone();
		mdeviceadapter = new DeviceAdapter(this, xqdevicelist);
		devicegridview.setAdapter(mdeviceadapter);
		devicegridview.setOnItemClickListener(this);
		devicegridview.setOnItemLongClickListener(this);
		
		
		
		
        //IEspDevice device = mUser.getUserDevice(deviceKey);
		
		Intent mftent = getIntent();
		mzonename = mftent.getStringExtra(Key.XQZONENAME_KEY);
		titlename.setText(mzonename);
		
		initDeviceList();
		
		mBraodcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter filter = new IntentFilter(EspStrings.Action.DEVICES_ARRIVE_PULLREFRESH);
        filter.addAction(EspStrings.Action.DEVICES_ARRIVE_STATEMACHINE);
        filter.addAction(EspStrings.Action.LOGIN_NEW_ACCOUNT);
        //mReciever 为监听回调方法
        mBraodcastManager.registerReceiver(mReciever, filter);
        
        //这里需要进行一次扫描网关信息  广播获得IP地址  和mac地址
        scanSta();
	}
	//这里扫描到的是网关设备信息
	  private void scanSta()
	    {
//	        if (!mStaScanning && !mRefreshing)
	        {
	        	showDialog();
	        	mUser.doActionRefreshStaDevices(false);
	        }
	    }
	  private void showDialog()
      {
          mDialog = new ProgressDialog(this);
          mDialog.setMessage(getString(R.string.esp_device_task_dialog_message));
          mDialog.setCanceledOnTouchOutside(false);
          mDialog.setOnDismissListener(this);
          mDialog.show();
      }
	  @Override
		public void onDismiss(DialogInterface arg0) {
			// TODO Auto-generated method stub
		  mDialog = null;
		}  
      private void releaseDialog()
      {
          if (mDialog != null)
          {
              mDialog.dismiss();
              mDialog = null;
          }
      }
	private void initDeviceList(){
		//devicelist.addAll(deviceDBManagerinstance.getAllDevice());
		//获取当前区域的信息
		IOTXqzoneDBManager zonemanager = IOTXqzoneDBManager.getInstance();
		if(mzonename!=null)
		{
			curzone = zonemanager.getzoneDB(mzonename);
			
			EspApplication.curzone = curzone;
		}
		else
		{
			Toast.makeText(getApplicationContext(), "不存在该区域", Toast.LENGTH_SHORT).show();
			finish();
		}
		mUser = BEspUser.getBuilder().getInstance();
		//加载属于该区域的设备  里面包含网关和普通设备
		xqdevicelist.clear();
		xqdevicelist.addAll(mUser.getXqZoneDeviceList(curzone.getId()));
		if(devicelist.size()>0)
		{
			
			
			
		}
		//加载网关信息
		gatelist.addAll(EspApplication.GetGlobalGW());
		
		//过滤出普通设备来
		xqcommdevicelist.clear();
		for(IEspDevice comdev: xqdevicelist)
		{
			if(comdev.getDeviceType() != EspDeviceType.GATEWAY){
				xqcommdevicelist.add(comdev);
			}
		}
		
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mBraodcastManager.unregisterReceiver(mReciever);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	
	class DeviceAdapter extends BaseAdapter {

		protected static final String TAG = "ZoneAdapter";
		private XqZoneDetailActivty mContext;
		private List<IEspDevice> mdeviceList = new ArrayList<IEspDevice>();
		private LayoutInflater mInflater;
		private float x, ux;
		private byte[] mContent;  
		private Bitmap myBitmap;
		
		//private boolean isDelete = false;
		
		public DeviceAdapter(Context context, List<IEspDevice> list){
			mContext = (XqZoneDetailActivty)context;
			mdeviceList = list;
			mInflater = LayoutInflater.from(context);
		}
		
		public void SetList(List<IEspDevice> list){
			mdeviceList = list;

		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			//Log.d(TAG, "get size is: " + mSwitchList.size());
			// +1 represent the device will be added
			return mdeviceList.size()+1;
		}

		@Override
		public Object getItem(int pos) {
			// TODO Auto-generated method stub
			
			if(pos < 0 || pos >= mdeviceList.size())
			{
				return null;
			}
			else{
				return mdeviceList.get(pos);
			}
		}

		@Override
		public long getItemId(int pos) {
			// TODO Auto-generated method stub
			Log.d(TAG, "get item id");
			return pos;
		}
		

		@Override
		public View getView(int pos, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ZoneHolder viewHolder = null;
			Log.e(TAG, "getView");
			
			//*
			if(convertView == null){
				viewHolder = new ZoneHolder();
				Log.d(TAG, "create convertview");
				convertView = mInflater.inflate(R.layout.xqzone_unit, null);
				
				
				
				{
					viewHolder.zoneicon = (ImageView)convertView.findViewById(R.id.zoneicon);
					viewHolder.zonename = (TextView) convertView.findViewById(R.id.zonename);
					viewHolder.childcount = (TextView) convertView.findViewById(R.id.childcount);
					
				}
				viewHolder.pos = pos;
				convertView.setTag(viewHolder);
				
			}
			else{
				
				viewHolder = (ZoneHolder) convertView.getTag();
				
			}
			// 设置高度和宽度    
			Point point = new Point();
	        getWindowManager().getDefaultDisplay().getSize(point);
			          
			convertView.setLayoutParams(new GridView.LayoutParams(point.x/2, point.x/2));
			viewHolder.childcount.setVisibility(View.GONE);
			//int pos = viewHolder.pos;
			
			//GoneDelete(holder);
			if(pos==mdeviceList.size()){
				viewHolder.zoneicon.setVisibility(View.VISIBLE);
				viewHolder.zonename.setVisibility(View.GONE);
				viewHolder.childcount.setVisibility(View.GONE);
				viewHolder.zoneicon.setImageResource(R.drawable.addicon);
			}
			else
			{
				
				IEspDevice mdevice = mdeviceList.get(pos);
				viewHolder.zonename.setVisibility(View.VISIBLE);
				viewHolder.zonename.setText(mdevice.getName());
				if(mdevice != null)
				{
					
					if(mdevice.getDeviceType() == EspDeviceType.GATEWAY){
						//if(mdevice.get)
						viewHolder.zoneicon.setImageResource(R.drawable.gateicon);
					}else{
						if(mdevice.getDeviceType() == EspDeviceType.PLUG_XQ)
						{
							EspStatusPlug statusPlug;
							 
							 statusPlug =(EspStatusPlug) ((EspDevicePlugXq)mdevice).getStatusPlug();
							
							boolean ison = statusPlug.isOn();
							if(ison == true)
								viewHolder.zoneicon.setImageResource(R.drawable.plug_icon);
							else
								viewHolder.zoneicon.setImageResource(R.drawable.plug_icon_off);
							Log.e("chazuo status", "plug status=" + ison);
						}else if(mdevice.getDeviceType() == EspDeviceType.PLUGTOUCH)
						{
							EspStatusPlug statusPlug;
							 
							 statusPlug =(EspStatusPlug) ((EspDevicePlugXq)mdevice).getStatusPlug();
							
							boolean ison = statusPlug.isOn();
							if(ison == true)
								viewHolder.zoneicon.setImageResource(R.drawable.plugtouch_on);
							else
								viewHolder.zoneicon.setImageResource(R.drawable.plugtouch_off);
							Log.e("chazuo status", "plug status=" + ison);
						}else if(mdevice.getDeviceType() == EspDeviceType.PLUGTOUCH_2
								|| mdevice.getDeviceType() == EspDeviceType.PLUGTOUCH_3
								|| mdevice.getDeviceType() == EspDeviceType.PLUGTOUCH_4){
							EspStatusPlug statusPlug;
							 statusPlug =(EspStatusPlug) ((EspDevicePlugTouchsXq)mdevice).getStatusPlug();
							
							boolean ison = statusPlug.isOn();
							if(ison == true)
								viewHolder.zoneicon.setImageResource(R.drawable.plugtouch_on);
							else
								viewHolder.zoneicon.setImageResource(R.drawable.plugtouch_off);
							Log.e("chazuo status", "plug status=" + ison);
						}else if(mdevice.getDeviceType() == EspDeviceType.CURTAIN){
							EspStatusCurtain statuscurtain;
							statuscurtain =(EspStatusCurtain) ((EspDeviceCurtainXq)mdevice).getStatusCurtain();
							
							int mison = statuscurtain.isOn();
							
							
							if(mison == 1)
								viewHolder.zoneicon.setImageResource(R.drawable.curtain_on);
							else if(mison == 2)
								viewHolder.zoneicon.setImageResource(R.drawable.curtain_off);
							else 
								viewHolder.zoneicon.setImageResource(R.drawable.curtain_off);
						}
						
					}
					viewHolder.zonename.setText(mdevice.getName());
				}
				else{
					viewHolder.zoneicon.setVisibility(View.GONE);
					viewHolder.zonename.setVisibility(View.GONE);
					viewHolder.childcount.setVisibility(View.GONE);
				}
			}
			return convertView;
		}


		class ZoneHolder{
		
			ImageView zoneicon;
			TextView zonename;
			
			TextView childcount;
			int pos = 0;
			ZoneHolder(){
				
			}
		}
	}


	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		if(view == back){
			finish();
		}else if(view == addzone){
			Intent minten = new Intent(this, AddZoneActivity.class);
			startActivityForResult(minten, REQ_ADDDEVICE);
		}
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(REQ_ADDDEVICE == requestCode && RESULT_OK==resultCode ){

			initDeviceList();
			mdeviceadapter.notifyDataSetChanged();
		}
	}
	private void ShowCurrentZone() {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int pos, long arg3) {
		// TODO Auto-generated method stub
		
		if(pos == xqdevicelist.size()){
			Intent mfintent = new Intent(this, ShareCaptureActivity.class);
			mfintent.putExtra(Key.XQZONENAME_KEY, mzonename);
			startActivityForResult(mfintent, REQ_ADDDEVICE);
			
		}else{
			
			mIEspDevice = xqdevicelist.get(pos);
			curespdev = mIEspDevice;
			if(mIEspDevice.getDeviceType() == EspDeviceType.GATEWAY){
				//Toast.makeText(getApplicationContext(), "", duration)
				//xqplug = (IEspDevicePlugXq)mIEspDevice;
				//准备往该网关添加设备
				/**
				 * 	把区域名字传递到下一个activity  并且把该网关的IP信息往下传递  方便做测试使用  testonoff
				 * */
				
			}
			else{
				

				log.error(mIEspDevice.getName() +"::" + mIEspDevice.getInetAddress());
				if(thiclent ==null && mIEspDevice.getInetAddress()!=null){
					new ConnetSocet(mIEspDevice.getInetAddress()).start();
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(thiclent !=null){
					String devicekey = mIEspDevice.getKey();
					String bssidstr  = devicekey.substring(0, 16);
					
					byte[]  bssid = HEX.decodeHexString(bssidstr);
					bssidstr = "";
					for(int j=0; j<8; j++){
						bssidstr = bssidstr  + " " + bssid[j];
						xqplugsenddata[6+j]=bssid[j];
					}
					Log.e("plug or kaiguan's bssid", bssidstr);
					
					if(mIEspDevice.getDeviceType() == EspDeviceType.PLUG_XQ)
					{
						EspStatusPlug statusPlug;
						 
						 statusPlug =(EspStatusPlug) ((EspDevicePlugXq)mIEspDevice).getStatusPlug();
						
						boolean ison = !statusPlug.isOn();
						xqplugsenddata[14] = (byte) ((ison==true)?1:0);
					}
					else if(mIEspDevice.getDeviceType() == EspDeviceType.PLUGTOUCH)
					{
						EspStatusPlug statusPlug;
						 
						 statusPlug =(EspStatusPlug) ((EspDevicePlugXq)mIEspDevice).getStatusPlug();
						
						boolean ison = !statusPlug.isOn();
						xqplugsenddata[14] = (byte) ((ison==true)?0x22:0x20);
					}else if(mIEspDevice.getDeviceType() == EspDeviceType.PLUGTOUCH_2
							|| mIEspDevice.getDeviceType() == EspDeviceType.PLUGTOUCH_3
							|| mIEspDevice.getDeviceType() == EspDeviceType.PLUGTOUCH_4){
						
						EspStatusPlug statusPlug;
						EspDevicePlugTouchsXq devtouchs =(EspDevicePlugTouchsXq)mIEspDevice; 
						 statusPlug =(EspStatusPlug) ((EspDevicePlugTouchsXq)mIEspDevice).getStatusPlug();
						 boolean ison = !statusPlug.isOn();
						 int posmove=0;
						 if (devtouchs.getPlugtouchnum()==1)
							 posmove = 2;
						 else if(devtouchs.getPlugtouchnum()==2)
							 posmove = 1;
						 else
							 posmove = devtouchs.getPlugtouchnum();
						 
						 int openvalue = 0x11<<posmove ;
						 int closevalue = 0x10<<posmove;
						 xqplugsenddata[14] = (byte) ((ison==true)?openvalue:closevalue);
						
					}else if(mIEspDevice.getDeviceType() == EspDeviceType.CURTAIN)
					{
						EspStatusCurtain statuscurtain;
						statuscurtain =(EspStatusCurtain) ((EspDeviceCurtainXq)mIEspDevice).getStatusCurtain();
						Log.e("CURTAIN or CURTAIN's bssid", bssidstr);
						int mison = statuscurtain.isOn();
						if(mison ==2)
							xqplugsenddata[14] = 1;
						else if(mison ==1)
							xqplugsenddata[14] = 2;
					
					}
					byte cheksum=0;
					for(int i=4; i<15; i++){
						cheksum += xqplugsenddata[i]; 
					}
					xqplugsenddata[15] = cheksum;
					
					try {
						sendString = new String( xqplugsenddata , "ISO-8859-1" );
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					new Plugonoff(this).execute(isOn);
				}else{
					Toast.makeText(this, R.string.esp_configure_direct_result_failed, Toast.LENGTH_SHORT).show();
		            return ;
				}
			}
		}
		
	}
	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View view, int pos,
			long arg3) {
		// TODO Auto-generated method stub
		if(pos == xqdevicelist.size()){
			Toast.makeText(this, R.string.esp_ui_edit_forbidden_toast, Toast.LENGTH_SHORT).show();
            return true;
		}
		IEspDevice device = xqdevicelist.get(pos);
        
        
        new AlertDialog.Builder(this).setItems(R.array.esp_ui_device_dialog_items, new ListItemDialogListener(device))
            .show();
        
        return true;
	}
	private class ListItemDialogListener implements DialogInterface.OnClickListener
    {
		private final int ITEM_ADDTIME_POSITION = 0;
		private final int ITEM_RENAME_POSITION = 1;
        
        private final int ITEM_DELETE_POSITION = 2;
        
        
        private IEspDevice mItemDevice;
        
        public ListItemDialogListener(IEspDevice device)
        {
            mItemDevice = device;
        }
        
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            switch (which)
            {
                case ITEM_RENAME_POSITION:
                    showRenameDialog();
                    break;
                case ITEM_DELETE_POSITION:
                    showDeleteDialog();
                    break;
                case ITEM_ADDTIME_POSITION:
                    showDeleteDialog();
                    break;
            }
        }
        
        private void showRenameDialog()
        {
            Context context = XqZoneDetailActivty.this;
            final EditText nameEdit = new EditText(context);
            nameEdit.setSingleLine();
            LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            nameEdit.setLayoutParams(lp);
            new AlertDialog.Builder(context).setView(nameEdit)
                .setTitle(mItemDevice.getName())
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
                {
                    
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        String newName = nameEdit.getText().toString();
                       // mUser.doActionRename(mItemDevice, newName);
                        Toast.makeText(getApplicationContext(), R.string.esp_ui_edit_forbidden_toast, Toast.LENGTH_SHORT).show();
                       
                    }
                    
                })
                .show();
        }
        
        private void showDeleteDialog()
        {
            Context context = XqZoneDetailActivty.this;
            new AlertDialog.Builder(context).setTitle(mItemDevice.getName())
                .setMessage(R.string.esp_ui_delete_message)
                .setNegativeButton(android.R.string.cancel, null)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
                {
                    
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                       /// mUser.doActionDelete(mItemDevice);
                    	Log.e("mItemDevice.getId", "mItemDevice.getId=" + mItemDevice.getId());
                    	deviceDBManagerinstance.delete(mItemDevice.getId());
                    	
                    	initDeviceList();
                    	mdeviceadapter.notifyDataSetChanged();
                    }
                })
                .show();
        }
    }
	 private class Plugonoff extends AsyncTask<Boolean, Void, Boolean> implements OnDismissListener
	    {
	        private Activity mActivity;
	        
	        private ProgressDialog mDialog;
	        
	      
	        
	        public Plugonoff(Activity activity)
	        {
	            mActivity = activity;
	           
	        }
	        
	       
	        @Override
	        protected void onPreExecute()
	        {
	           
	            
	            showDialog();
	        }
	        
	        @Override
	        protected Boolean doInBackground(Boolean... ison)
	        {
	        	//Log.e("getInetAddress", "selectedgate.getInetAddress().getHostName()=" + selectedgate.getInetAddress().getHostAddress());
	        	try {
					thiclent.writeRequest(sendString);
					thiclent.setSoTimeout(3000);
					//等待响应数据返回
					String result = thiclent.readResponse();
					byte[] resultbyte = result.getBytes(InputStreamUtils.DEFAULT_CHARSET);
					if(curespdev.getDeviceType().getSerial() == EspDeviceType.PLUG_XQ.getSerial())
					{
						
						if(resultbyte.length ==16){
							if(resultbyte[0] == (byte)0xfe && resultbyte[1]==(byte)0x7e){
								EspStatusPlug statusPlug;
								 
								 statusPlug =(EspStatusPlug) ((EspDevicePlugXq)curespdev).getStatusPlug();
								Log.e("EspDevicePlug", "(EspDevicePlugXq)curespdev).getStatusPlug()=" + statusPlug);
								
				                if(resultbyte[14] ==1)
									statusPlug.setIsOn(true);
								else if(resultbyte[14] ==0)
									statusPlug.setIsOn(false);
							}
						}
						return true;
					}
					else if(curespdev.getDeviceType() == EspDeviceType.PLUGTOUCH)
					{
						
						if(resultbyte.length ==16){
							if(resultbyte[0] == (byte)0xfe && resultbyte[1]==(byte)0x7e){
								EspStatusPlug statusPlug;
								 
								 statusPlug =(EspStatusPlug) ((EspDevicePlugXq)curespdev).getStatusPlug();
								Log.e("EspDevicePlug", "(EspDevicePlugXq)curespdev).getStatusPlug()=" + statusPlug);
								
				                if(resultbyte[14] ==0x22)
									statusPlug.setIsOn(true);
								else if(resultbyte[14] ==0x20)
									statusPlug.setIsOn(false);
							}
						}
						return true;
					}
					else if(mIEspDevice.getDeviceType() == EspDeviceType.PLUGTOUCH_2
							|| mIEspDevice.getDeviceType() == EspDeviceType.PLUGTOUCH_3
							|| mIEspDevice.getDeviceType() == EspDeviceType.PLUGTOUCH_4)
					{
						
						if(resultbyte.length ==16){
							if(resultbyte[0] == (byte)0xfe && resultbyte[1]==(byte)0x7e){
							
								EspStatusPlug statusPlug;
								EspDevicePlugTouchsXq mdev = (EspDevicePlugTouchsXq)curespdev;
								 statusPlug =(EspStatusPlug) ((EspDevicePlugTouchsXq)curespdev).getStatusPlug();
								Log.e("EspDevicePlug", "(EspDevicePlugXq)curespdev).getStatusPlug()=" + statusPlug);
								int respvalueOn = 0x11;
								if (mdev.getPlugtouchnum()==1)
									respvalueOn = 0x11<<2;
								 else if(mdev.getPlugtouchnum()==2)
									 respvalueOn = 0x11<<1;
								 else
									 respvalueOn = 0x11<<mdev.getPlugtouchnum();
								//int respvalueOff = 0x10<<mdev.getPlugtouchnum();
				                if((resultbyte[14] & (byte)respvalueOn & 0x0f) !=0  )
									statusPlug.setIsOn(true);
								else if((resultbyte[14] & (byte)respvalueOn & 0x0f) ==0  )
									statusPlug.setIsOn(false);
							}
						}
						
						return true;
					}
					else if(mIEspDevice.getDeviceType() == EspDeviceType.CURTAIN)
					{
						
						if(resultbyte.length ==16){
							if(resultbyte[0] == (byte)0xfe && resultbyte[1]==(byte)0x7e){
							
								EspStatusCurtain statuscurtain;
								EspDeviceCurtainXq mdev = (EspDeviceCurtainXq)curespdev;
								
								statuscurtain =(EspStatusCurtain) ((EspDeviceCurtainXq)curespdev).getStatusCurtain();
								
								Log.e("EspDevicePlug", "(EspDevicePlugXq)curespdev).getStatusPlug()=" + statuscurtain);
								
								statuscurtain.setIsOn(resultbyte[14]);
								
							}
						}
						
						return true;
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        	return false;
	        }
	        
	        @Override
	        protected void onPostExecute(Boolean result)
	        {
	            //log.debug("DeviceTask result = " + result);
	            releaseDialog();
	           
	            if(result == true){
	            	mdeviceadapter.notifyDataSetChanged();
	            }
	        }
	        
	        private void showDialog()
	        {
	            mDialog = new ProgressDialog(mActivity);
	            mDialog.setMessage(getString(R.string.esp_device_task_dialog_message));
	            mDialog.setCanceledOnTouchOutside(false);
	            mDialog.setOnDismissListener(this);
	            mDialog.show();
	        }
	        
	        private void releaseDialog()
	        {
	            if (mDialog != null)
	            {
	                mDialog.dismiss();
	                mDialog = null;
	            }
	        }
	        
	        @Override
	        public void onDismiss(DialogInterface dialog)
	        {
	            cancel(true);
	            mDialog = null;
	        }

			
	    }
	  private BroadcastReceiver mReciever = new BroadcastReceiver()
	    {
	        
	        @Override
	        public void onReceive(Context context, Intent intent)
	        {
	            final String action = intent.getAction();
	            if (action.equals(EspStrings.Action.DEVICES_ARRIVE_STATEMACHINE))
	            {
	                //添加
	            	log.error("Receive Broadcast DEVICES_ARRIVE_STATEMACHINE");
	                mUser.doActionDevicesUpdated(true);
	                
	                initDeviceList();
	                updateGWDeviceList();
	                mdeviceadapter.notifyDataSetChanged();
	            
	            }
	            if(action.equals(EspStrings.Action.DEVICES_ARRIVE_PULLREFRESH)){
	            	Toast.makeText(getApplicationContext(), "扫描网关结束", Toast.LENGTH_SHORT).show();
	            	//更新网关的IP信息
	            	gatelocallist = EspDeviceCacheHandler.getInstance().GetGateIp();
	            	
	            	if(gatelocallist!=null && gatelocallist.size()>0){
	            		for(IOTAddress gate: gatelocallist){
	            			for(EspDeviceGateway owngate: gatelist){
	            				if(owngate.getBssid().equals(gate.getBSSID())){
	            					
	            					String hostname = gate.getInetAddress().getHostName();
	            					owngate.setInetAddress(gate.getInetAddress());
	            					owngate.SetInetAddress(gate.getInetAddress());
	            				}
	            			}
	            		}
	            	}
	            	updatedevInetAddress();
	            	releaseDialog();
	            }
	        }

			private void updatedevInetAddress() {
				// TODO Auto-generated method stub
				if(gatelist!=null && gatelist.size()>0){
            		
            		
            		//update the no gateway ip 
            		for(EspDeviceGateway owngate: gatelist){
            			if(null == owngate.getInetAddress())
            				continue;
            			for(IEspDevice comdev:xqdevicelist){
            				if(comdev.getDeviceType() == EspDeviceType.GATEWAY)
            					continue;
            				if(comdev.getBssid().equals(owngate.getBssid())){
            					comdev.setInetAddress(owngate.getInetAddress());
            				}
            			}
            		}
            	}
			}
	        
	    };
	    private void updateGWDeviceList()
	    {
	       
	    	//检出属于该区域下的所有设备
	    	for(IEspDevice dev: xqdevicelist)
	    	{
	    		boolean isadd =true;
	    		if(dev.getDeviceType().getSerial() == EspDeviceType.GATEWAY.getSerial()){
	    			for(EspDeviceGateway gw: gatelist){
	    				if(gw.getId() == dev.getId()){
	    					isadd = false;
	    					break;
	    				}
	    			}
	    		}else
	    			continue;
	    		if(isadd){
	    			EspApplication.SetGlobalGW((EspDeviceGateway)dev);
	    		}
	    	}
	        //  	xqdevicelist.add(device);
	        
	    }
	    private class ConnetSocet extends Thread{
	    	InetAddress host;
	    	public ConnetSocet(InetAddress iphost){
	    		host =iphost;
	    	}
			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				thiclent = new EspSocketClient();
				thiclent.connect(host.getHostAddress(), 1206);
				
			}
			
		}


		  
	    
}
